package com.ext.aic.utils.device;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ContentResolver;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.Settings;
import android.text.TextUtils;
import android.text.format.Formatter;

import com.ext.aic.beans.DeviceMeta;
import com.eyinfo.android_pure_utils.ObjectManager;
import com.eyinfo.android_pure_utils.encryption.Md5Utils;
import com.eyinfo.android_pure_utils.logs.Logger;
import com.eyinfo.android_pure_utils.utils.ConvertUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Locale;

/**
 * Author lijinghuan
 * Email:ljh0576123@163.com
 * CreateTime:2020/10/27
 * Description:
 * Modifier:
 * ModifyContent:
 */
public class DeviceHelper {

    private String[] units = {"B", "KB", "MB", "GB", "TB"};

    @SuppressLint("HardwareIds")
    public String generateDeviceUnique(Context context) {
        StringBuilder builder = collectDeviceData();
        ContentResolver contentResolver = context.getContentResolver();
        String androId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID);
        builder.append(androId);
        return Md5Utils.encryptForHex(builder.toString());
    }

    private StringBuilder collectDeviceData() {
        StringBuilder builder = new StringBuilder("35");
        builder.append(sumChars(Build.BOARD) % 10);
        builder.append(sumChars(Build.BRAND) % 10);
        builder.append(sumChars(getAbIS()) % 10);
        builder.append(sumChars(Build.DEVICE) % 10);
        builder.append(sumChars(Build.DISPLAY) % 10);
        builder.append(sumChars(Build.HOST) % 10);
        builder.append(sumChars(Build.ID) % 10);
        builder.append(sumChars(Build.MANUFACTURER) % 10);
        builder.append(sumChars(Build.MODEL) % 10);
        builder.append(sumChars(Build.PRODUCT) % 10);
        builder.append(sumChars(Build.TAGS) % 10);
        builder.append(sumChars(Build.TYPE) % 10);
        builder.append(sumChars(Build.USER) % 10);
        return builder;
    }

    private int sumChars(String s) {
        int sum = 0;
        for (int i = 0; i < s.length(); i++) {
            sum += s.charAt(i);
        }
        return sum;
    }

    private String capitalize(String str) {
        if (TextUtils.isEmpty(str)) {
            return str;
        }
        char[] arr = str.toCharArray();
        boolean capitalizeNext = true;
        StringBuilder phrase = new StringBuilder();
        for (char c : arr) {
            if (capitalizeNext && Character.isLetter(c)) {
                phrase.append(Character.toUpperCase(c));
                capitalizeNext = false;
                continue;
            } else if (Character.isWhitespace(c)) {
                capitalizeNext = true;
            }
            phrase.append(c);
        }
        return phrase.toString();
    }

    private String getLinuxCore_Ver() {
        Process process = null;
        String kernelVersion = "";
        try {
            process = Runtime.getRuntime().exec("cat /proc/version");
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream outs = process.getInputStream();
        InputStreamReader isrout = new InputStreamReader(outs);
        BufferedReader brout = new BufferedReader(isrout, 8 * 1024);
        StringBuilder result = new StringBuilder();
        String line;
        try {
            while ((line = brout.readLine()) != null) {
                result.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (result.length() > 0) {
                String Keyword = "version ";
                int index = result.indexOf(Keyword);
                line = result.substring(index + Keyword.length());
                index = line.indexOf(" ");
                kernelVersion = line.substring(0, index);
            }
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }
        return kernelVersion;
    }

    private String getInner_Ver() {
        String ver = "";
        if (Build.DISPLAY.contains(Build.VERSION.INCREMENTAL)) {
            ver = Build.DISPLAY;
        } else {
            ver = Build.VERSION.INCREMENTAL;
        }
        return ver;
    }

    public DeviceMeta getSysDeviceInfo(Context context) {
        DeviceMeta response = new DeviceMeta();
        response.setBoard(Build.BOARD);
        response.setBrand(Build.BRAND);
        response.setCpuABI(getAbIS());
        response.setDevice(Build.DEVICE);
        response.setDisplay(Build.DISPLAY);
        response.setHost(Build.HOST);
        response.setId(Build.ID);
        response.setManufacturer(Build.MANUFACTURER);
        response.setModel(Build.MODEL);
        response.setProduct(Build.PRODUCT);
        response.setTags(Build.TAGS);
        response.setType(Build.TYPE);
        response.setUser(Build.USER);
        //屏幕分辨率
        int screenWidth = ObjectManager.getScreenWidth(context);
        int screenHeight = ObjectManager.getScreenHeight(context);
        response.setResolution(String.format("%sx%s", screenWidth, screenHeight));
        return response;
    }

    public String getLocalIpAddress(Context context) {
        try {
            Context applicationContext = context.getApplicationContext();
            WifiManager wifiManager = (WifiManager) applicationContext.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipInt = wifiInfo.getIpAddress();
            return (ipInt & 0xFF) + "." +
                    ((ipInt >> 8) & 0xFF) + "." +
                    ((ipInt >> 16) & 0xFF) + "." +
                    ((ipInt >> 24) & 0xFF);
        } catch (Exception e) {
            Logger.error(e);
        }
        return "";
    }

    public String getTotalMemory(Context context) {
        String str1 = "/proc/meminfo";
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
            //读取meminfo第一行，系统总内存大小
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            // 获得系统总内存，单位是KB
            int i = Integer.parseInt(arrayOfString[1]);
            //int值乘以1024转换为long类型
            initial_memory = i * 1024L;
            localBufferedReader.close();
        } catch (IOException e) {
            Logger.error(e);
        }
        //Byte转换为KB或者MB，内存大小规格化
        return Formatter.formatFileSize(context, initial_memory);
    }

    public String getAvailMemory(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return Formatter.formatFileSize(context, mi.availMem);
    }

    public String getAvailableStorageSize() {
        StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        long blockSize = statFs.getBlockSize();
        long availableCount = statFs.getAvailableBlocks();
        float availableSize = blockSize * availableCount;
        return getUnit(availableSize);
    }

    public String setRemainStorageSize() {
        StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        long blockSize = statFs.getBlockSize();
        long availableCount = statFs.getAvailableBlocks();

        long freeBlocks = statFs.getFreeBlocks();
        float availableSize = blockSize * availableCount;
        float freeSize = blockSize * freeBlocks;
        float unavailableSize = freeSize - availableSize;
        return getUnit(unavailableSize);
    }


    public String getStorageSize() {
        StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        //存储块总数量
        long blockCount = statFs.getBlockCount();
        //块大小
        long blockSize = statFs.getBlockSize();
        long availableCount = statFs.getAvailableBlocks();
        return getUnit(blockSize * blockCount);
    }

    private String getUnit(float size) {
        int index = 0;
        while (size > 1024 && index < 4) {
            size = size / 1024;
            index++;
        }
        return String.format(Locale.getDefault(), " %.2f %s", size, units[index]);
    }

    private String getAbIS() {
        String[] supported32BitABis = Build.SUPPORTED_32_BIT_ABIS;
        String[] supported64BitABis = Build.SUPPORTED_64_BIT_ABIS;
        String[] array = new String[supported32BitABis.length + supported64BitABis.length];
        int position = 0;
        for (String supported32BitAbi : supported32BitABis) {
            array[position] = supported32BitAbi + ";";
            position++;
        }
        for (String supported64BitAbi : supported64BitABis) {
            array[position] = supported64BitAbi + ";";
            position++;
        }
        return ConvertUtils.toJoin(array, "");
    }

    @SuppressLint("HardwareIds")
    public String getAndroidId(Context context) {
        try {
            return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (Exception e) {
            return null;
        }
    }
}
